package com.xcl.seckill.service.Impl;

import com.xcl.seckill.dao.OrderDOMapper;
import com.xcl.seckill.dao.SequenceInfoDOMapper;
import com.xcl.seckill.error.BusinessException;
import com.xcl.seckill.error.EmBusinessError;
import com.xcl.seckill.model.OrderDO;
import com.xcl.seckill.model.SequenceInfoDO;
import com.xcl.seckill.service.ItemService;
import com.xcl.seckill.service.OrderService;
import com.xcl.seckill.service.UserService;
import com.xcl.seckill.service.domain.ItemModel;
import com.xcl.seckill.service.domain.OrderModel;
import com.xcl.seckill.service.domain.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    SequenceInfoDOMapper sequenceInfoDOMapper;
   @Autowired
   ItemService itemService;
   @Autowired
    UserService userService;
   @Autowired
    OrderDOMapper orderDOMapper;

    @Override
    @Transactional
    public OrderModel createOrder(Integer userId, Integer itemId,Integer promoId, Integer amount) throws BusinessException {
        ItemModel itemModel=itemService.getItemById(itemId);
        if(itemModel==null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"商品信息不存在");
        }
        UserModel userModel=userService.getUserById(userId);
        if(userModel==null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"用户信息不正确");
        }
        if(amount<=0||amount>99){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"数量信息不正确");
        }
    if (promoId!=null) {
         if (promoId.intValue() != itemModel.getPromoModel().getId()) {
        throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "活动信息不正确");
    } else if (itemModel.getPromoModel().getStatus().intValue() != 2) {
        throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "活动还未开始");
    }
}
        boolean result=itemService.decreateStock(itemId,amount);
        if(!result){
        throw new BusinessException(EmBusinessError.STOCK_NOT_ENOUGH);
        }
        OrderModel orderModel= new OrderModel();
        orderModel.setUserId(userId);
        orderModel.setItemId(itemId);
        orderModel.setAmount(amount);
        if (promoId!=null){
            orderModel.setPromoId(promoId);
            orderModel.setItemPrice(itemModel.getPromoModel().getPromoItemPrice());
        }else {
            orderModel.setItemPrice(itemModel.getPrice());
        }
        orderModel.setOrderPrice(orderModel.getItemPrice().multiply( new BigDecimal(amount)));
        orderModel.setId(generateOrderNo());
        OrderDO orderDO=converFromOrderModel(orderModel);
        orderDO.setOrderAccount(orderModel.getOrderPrice());

        orderDOMapper.insertSelective(orderDO);
        itemService.increase(itemId,amount);

        return orderModel;
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
     String generateOrderNo(){
        StringBuilder stringBuilde=new StringBuilder();
        LocalDateTime now=LocalDateTime.now();
      String nowDate= now.format(DateTimeFormatter.ISO_DATE).replace("-","");
       stringBuilde.append(nowDate);
        int sequence = 0;
        SequenceInfoDO sequenceInfoDO=sequenceInfoDOMapper.getSequenceInfo("order_info");
       sequence= sequenceInfoDO.getCurrentValue();
        sequenceInfoDO.setCurrentValue(sequenceInfoDO.getCurrentValue()+sequenceInfoDO.getStep());
        sequenceInfoDOMapper.updateByPrimaryKeySelective(sequenceInfoDO);
        String sequenceStr=String.valueOf(sequence);
        for(int i=0;i<6-sequenceStr.length();i++){
            stringBuilde.append(0);
        }
        stringBuilde.append(sequenceStr);
    stringBuilde.append("00");
    return stringBuilde.toString();
    }
    private OrderDO converFromOrderModel(OrderModel orderModel){
        if (orderModel==null){
            return null;
        }
        OrderDO orderDO=new OrderDO();
        BeanUtils.copyProperties(orderModel,orderDO);
        return orderDO;
    }
}
